const { Op } = require("sequelize");
const Carts = require("../model/cartsModel");
const Goods = require("../model/goodsModel");
class CartsService {
  async createOrUpdate(user_id, goods_id) {
    const res = await Carts.findOne({
      where: {
        [Op.and]: {
          user_id,
          goods_id,
        },
      },
    });

    if (res) {
      await res.increment("number");
      return await res.reload();
    } else {
      // 创建新购物车项时提供 number 和 selected 字段
      return await Carts.create({
        user_id,
        goods_id,
        number: 1, // 初始数量
        selected: true, // 默认选中
      });
    }
  }
  async findCarts(pageNum, pageSize) {
    const offset = (pageNum - 1) * pageSize;
    const { count, rows } = await Carts.findAndCountAll({
      attributes: ["id", "number", "selected"],
      offset: offset,
      limit: pageSize * 1,
      include: {
        model: Goods,
        as: "goods_info",
        attributes: ["id", "goods_name", "goods_price", "goods_img"],
        required: false, // 让 include 表格在查询结果中返回 null
      },
    });
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }
  async updateCarts(params) {
    const { id, number, selected } = params;
    const res = await Carts.findByPk(id);
    if (!res) {
      return "";
    }
    number !== undefined ? (res.number = number) : "";
    if (selected !== undefined) {
      res.selected = selected;
    }
    return await res.save();
  }
  async removeCarts(ids) {
    return await Carts.destroy({
      where: {
        id: { [Op.in]: ids },
      },
    });
  }
  async selectAllCarts(user_id) {
    return await Carts.update(
      { selected: true },
      {
        where: {
          user_id,
        },
      }
    );
  }
  async unselectAllCarts(user_id) {
    return await Carts.update(
      { selected: false },
      {
        where: {
          user_id,
        },
      }
    );
  }
}
module.exports = new CartsService();
